import 'package:flutter/material.dart';
import 'package:flutterproject/mvvm/base/base_controller.dart';
import 'package:flutterproject/page/mine/children/order/data/order_list_bean.dart';
import 'package:flutterproject/util/address_manager.dart';
import 'package:flutterproject/util/dialog_toast/dialog_util.dart';
import 'package:flutterproject/util/dialog_toast/toast_util.dart';
import 'package:flutterproject/util/http/http_client.dart';
import 'package:flutterproject/util/http/http_exception.dart';
import 'package:get/get.dart';

class OrderListController extends BaseController {
  HttpClient client = Get.find<HttpClient>();
  OrderListBean? orderDetailBean = OrderListBean();
  List<OrderListList> list = [];
  int currentIndex = 0;

  @override
  void onInit() {
    super.onInit();
    currentIndex = Get.arguments;
    getOrderList();
  }

  final List<Tab> myTabs = <Tab>[
    Tab(text: '待付款'),
    Tab(text: '待发货'),
    Tab(text: '已发货'),
    Tab(text: '已完成'),
  ];

  /// 获取订单列表
  Future getOrderList() async {
    try {
      DialogUtil.showLoading();
      orderDetailBean =
          await client.get<OrderListBean>(AddressManager.orderList);
      list = orderDetailBean?.list
              ?.where((element) => element.state == (currentIndex + 1))
              .toList() ??
          [];
      update();
      return true;
    } on HttpException catch (e) {
      ToastUtil.showFailed(e.message);
      return false;
    } finally {
      DialogUtil.dismiss();
    }
  }

  Future<void> changeIndex(int index) async {
    currentIndex = index;
    if (orderDetailBean == null) {
      await getOrderList();
    } else {
      list = orderDetailBean?.list
              ?.where((element) => element.state == (currentIndex + 1))
              .toList() ??
          [];
      update();
    }
  }

  String getStatusStr(int? state) {
    switch (state) {
      case 1:
        return "待付款";
      case 2:
        return "待发货";
      case 3:
        return "已发货";
      case 4:
        return "完成";
      default:
        return "未知状态";
    }
  }
}
